﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AMiao.Tool.Tasks.Demo
{
    /// <summary>
    /// 关于并行计算的demo
    /// </summary>
    public class ParallelDemo
    {
        public static async Task ParallelAsync()
        {
            ParallelOptions parallelOptions = new ParallelOptions();
            parallelOptions.MaxDegreeOfParallelism = 2; // 设置最大并行度为 2

            var items = Enumerable.Range(0, 10).ToList();


            ///使用异步此方式，不会有线程等待，
            Parallel.ForEach(items, parallelOptions, async item =>
            {
                Console.WriteLine($"Parallel参数 {item},线程id: {Thread.CurrentThread.ManagedThreadId}");
                await Task.Run(() => ProcessItemAsync(item));
            });

            //同步执行
            //Parallel.ForEach(items, parallelOptions, item =>
            //{
            //    Console.WriteLine($"Parallel参数 {item},线程id: {Thread.CurrentThread.ManagedThreadId}");
            //    ProcessItemSync(item);
            //});

        }

        private static async Task ProcessItemAsync(int item)
        {
            Console.WriteLine($"开始执行参数 {item},线程id: {Thread.CurrentThread.ManagedThreadId}");
            // 模拟与任务一起工作。延迟1秒
            await Task.Delay(TimeSpan.FromSeconds(1));
            Console.WriteLine($"完成参数 {item}执,线程id: {Thread.CurrentThread.ManagedThreadId}");
        }


        private static void ProcessItemSync(int item)
        {
            Console.WriteLine($"开始执行参数 {item},线程id: {Thread.CurrentThread.ManagedThreadId}");
            // 模拟与任务一项工作
            Thread.Sleep(1000);
            Console.WriteLine($"完成参数 {item}执,线程id: {Thread.CurrentThread.ManagedThreadId}");
        }
    }
}
